
    <div>
        <form class="layui-form" action="">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-sm" lay-event="save" id="save">
                <i class="layui-icon layui-icon-save"></i>
                <span>保存</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="add" id="add">
                <i class="layui-icon layui-icon-add-1"></i>
                <span>添加</span>
            </a>
            <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del" id="del">
                <i class="layui-icon layui-icon-delete"></i>
                <span>删除</span>
            </a>
        </div>
        <table style="width:100%;text-align: center;" id="fieldTable" class="layui-table" >
            <thead>
            <tr>
                <th style="width: 20px;text-align: center"><input type="checkbox" id="chkall" lay-skin="primary"></th>
                <th style="text-align: center">节点名</th>
                <th style="text-align: center">所选字段</th>
                <th style="text-align: center">所选值</th>
                <th style="text-align: center">变换字段</th>
                <th style="text-align: center">变换类型</th>
            </tr>
            </thead>
            <tbody>
            <tr class="empty">
                <td colspan="6">
                    <div class="loading-div">当前没有记录。</div>
                </td>
            </tr>
            </tbody>
        </table>
        </form>
    </div>

    <script>
        layui.use(['table','setter','util','layer','form'], function () {
            var table = layui.table;
            var setter = layui.setter;
            var $ = layui.$;
            var form = layui.form;
            var layer = layui.layer;
            form.render();

            var nodeSelectHtml = '',
                choseFieldsHtml = '',
                changeFieldsHtml = '';

            //流程定义id
            var modelId = '${modelId!}';
            /*节点信息json格式*/
            var nodeSets = '${nodeSets}';
            /*表单的所有输入框*/
            var fields = '${fields}';

            var vValSpan = '<div style="position: relative;margin-right: 80px;">\n' +
                '    <select name="changeType" id="changeType" lay-filter="changeType">\n' +
                '        <option value="1">隐藏</option>\n' +
                '        <option value="2">显示</option>\n' +
                '        <option value="3">只读</option>\n' +
                '        <option value="4">非只读</option>\n' +
                '        <option value="5">必填</option>\n' +
                '        <option value="6">非必填</option>\n' +
                '        <option value="7">置空</option>\n' +
                '    </select>' +
                '<a class="link done" style="display:none; position: absolute;right: -70px;top: 10px;cursor: pointer;">级联设置</a>\n'+
                '<div style="display: none;" class="doneLayer"></div>\n'+
                '</div>';

            //生成guid
            function guidGen(){
                var G = function(){
                    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
                };
                return (G()+G()+"-"+G()+"-"+G()+"-"+G()+G()+G());
            }
            var allFields = new Array();
            allFields.push(${allFields});
            var fields = new Array();
            fields.push(${fields});
            var modelId = '${modelId}';
            var formKey = '${formKey}';
            var sxzOption = '';
            //初始化
            $.ajax({
                url: serverPath.workflowPath + setter.workflowLinkPath + "bpmGangedSet/list",
                type: "post",
                data: {
                    modelId:modelId
                },
                dataType: 'json',
                success: function (data) {
                    if (data.code==0){
                        $("tr.empty").remove();
                        $.each(data.data,function (index,value) {
                            $('#fieldTable').append(getNewTr(value.id,value));
                            $('#fieldTable tbody tr').eq(index).find('select[name=nodeId]').val(value.nodeId);
                            var chooseField = JSON.parse(value.chooseField);
                            $.each(chooseField,function (k,v) {
                                if(k>0){
                                    addChooseItem($('#fieldTable tbody tr').eq(index).children('td').eq(2).find('.add-choose-field'));
                                }
                                    $('#fieldTable tbody tr').eq(index).children('td').eq(2).find('select').eq(k).val(v.id);
                                    var elem = $('#fieldTable tbody tr').eq(index).children('td').eq(2).find('select').eq(k);
                                    var sxzdKey = $(elem).parent('div').attr('key');
                                    var sxzOptions='';
                                    $.each(fields[0][0].fields,function (k,vs) {
                                        if (v.id==vs.fieldId) {
                                            $.each(vs.options,function (index,values) {
                                                sxzOptions += '<option value="'+values.key+'">'+values.value+'</option>';
                                            })
                                        }
                                    });
                                    $.each($(elem).parent().parent('td').next().children('div'),function (k,vz) {
                                        if ($(vz).attr('key')==sxzdKey) {
                                            $(this).children('select').html('')
                                            $(this).children('select').append(sxzOptions)
                                            form.render('select'); //更新全部
                                        }
                                    });
                            });
                            var changeField = JSON.parse(value.changeField);
                            //需完善
                            $.each(changeField,function (k,v) {
                                if(k>0){
                                    addChangeItem($('#fieldTable tbody tr').eq(index).children('td').eq(4).find('.add-change-field'));
                                }
                                $('#fieldTable tbody tr').eq(index).children('td').eq(4).find('select').eq(k).val(v.id);
                                var elem = $('#fieldTable tbody tr').eq(index).children('td').eq(4).find('select').eq(k);
                                var bhzdKey = $(elem).parent('div').attr('key');
                                $.each($(elem).parent().parent('td').next().children('div'),function (k,vz) {
                                    if ($(vz).attr('key')==bhzdKey) {
                                        if (v.id=='c43a3e6209714a2e9070be686b2ca170'){
                                            $(this).find('select').append('<option value="8" style="display: none">级联</option>');
                                            if (v.type==8){
                                                $(this).find('.done').show();
                                            }
                                        }
                                        $(this).find('select').val(v.type)
                                        form.render('select'); //更新全部
                                    }
                                });
                            });
                        })
                        form.render(); //更新全部
                    }else {
                        layer.msg(data.msg,{icon:5});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                }
            })
            $.each(fields[0][0].fields,function (k,v) {
                choseFieldsHtml += '<option value="'+v.fieldId+'">'+v.fieldDesc+'</option>';
                if (k==0){
                    $.each(v.options,function (index,value) {
                        sxzOption += '<option value="'+value.key+'">'+value.value+'</option>';
                    });
                }
            });
            $.each(allFields[0][0].fields,function (k,v) {
                changeFieldsHtml += '<option fieldtype="'+v.type+'" value="'+v.fieldId+'">'+v.fieldDesc+'</option>'
            })
            //单元格内容
            function getNewTr(id,data){
                var guid1 = guidGen(),
                    guid2 = guidGen();
                var nodeName = '<select name="nodeId"><#list nodeSerList as nodeList><option value="${nodeList.setId}">${nodeList.nodeName}</option></#list><option>起始节点</option></select>'
                var td1Input = $('<input type="checkbox" lay-skin="primary" class="chk" name="id" value="" />').attr('value',id),
                    td1 = $('<td rowspan="1"></td>').append(td1Input),
                    td2 = $('<td rowspan="1"></td>').html(nodeName),
                    td3 = $('<td></td>'),
                    td4 = $('<td></td>'),
                    vSelect = $('<select class="fieldsSelect" lay-filter="fieldsSelect5" name="change-field"></select>').html(changeFieldsHtml),
                    vSpan = $('<div style="position: relative;margin-right: 80px;" class="change-panel"></div>').attr("key",guid2).append(vSelect).append('<a href="javascript:;" class="add-change-field" style="color: blue;position: absolute;right: -40px;top: 10px;">添加</a>'),
                    td5 = $('<td></td>').append(vSpan),
                    vValSpanDiv = $('<div></div>').append(vValSpan).attr("key",guid2),
                    td6 = $('<td></td>').html(vValSpanDiv);
                if(data||id=='0'){
                    var cSelect = $('<select class="fieldsSelect" lay-filter="fieldsSelect" name="choose-field"></select>').html(choseFieldsHtml),
                        cSpan = $('<div style="position: relative;margin-right: 80px;" class="change-panel"></div>').attr("key",guid1).append(cSelect).append('<a href="javascript:;" class="add-choose-field" style="margin-right: 4px;color: blue;position: absolute;right: -40px;top: 10px;">添加</a><a href="javascript:;" class="remove-field" style="color: red;position: absolute;right: -80px;top: 10px;">删除</a>');
                    td3.append(cSpan);
                    var cVal = $('<div></div>').attr("key",guid1).append('<select>'+sxzOption+'</select>');
                    td4.append(cVal);
                }
                var	newTr = $('<tr></tr>').append(td1).append(td2).append(td3).append(td4).append(td5).append(td6);
                return newTr;
            }
            //监听select选择
            form.on('select(fieldsSelect)', function(data){
                var sxzdKey = $(data.elem).parent('div').attr('key');
                var sxzOptions='';
                $.each(fields[0][0].fields,function (k,v) {
                    if (data.value==v.fieldId) {
                        $.each(v.options,function (index,value) {
                            sxzOptions += '<option value="'+value.key+'">'+value.value+'</option>';
                        })
                    }
                });
                $.each($(data.elem).parent().parent('td').next().children('div'),function (k,v) {
                    if ($(v).attr('key')==sxzdKey) {
                        $(this).children('select').html('')
                        $(this).children('select').append(sxzOptions)
                        form.render('select'); //更新全部
                    }
                });
            });
            //监听select5选择
                form.on('select(fieldsSelect5)', function(data){
                    var bhzdKey = $(data.elem).parent('div').attr('key');
                    if (data.value=='c43a3e6209714a2e9070be686b2ca170'){
                        $.each($(data.elem).parent().parent('td').next().children('div'),function (k,v) {
                            if ($(v).attr('key')==bhzdKey) {
                                $(this).find('select').append('<option value="8" style="display: none">级联</option>');
                                form.render('select'); //更新全部
                            }
                        });
                    }else {
                        $.each($(data.elem).parent().parent('td').next().children('div'),function (k,v) {
                            if ($(v).attr('key')==bhzdKey) {
                                $.each($(this).find('option'),function (k,v) {
                                    if ($(v).val()==8){
                                        $(this).remove();
                                        form.render('select'); //更新全部
                                    }
                                })
                            }
                        });
                    }
                });
            //添加选择框字段值（包括选择值）
            function addChooseItem(t) {
                var td = t.parent().parent("td"),
                    nextTd = td.next(),
                    guid = guidGen();

                var cSelect = $('<select class="fieldsSelect" lay-filter="fieldsSelect" name="choose-field"></select>').html(choseFieldsHtml),
                    cSpan = $('<div style="position: relative;margin-right: 80px;" class="change-panel"></div>').attr("key",guid).append(cSelect).append('<a href="javascript:;" class="remove-field" style="color: red;position: absolute;top: 10px; right: -40px;">删除</a>');

                td.append('<p><br /></p>').append(cSpan);

                var vSelect = $('<select>'+sxzOption+'</select>'),
                    vSpan = $('<div></div>').attr("key",guid).append(vSelect);

                nextTd.append('<p><br /></p>').append(vSpan);
            }

            //添加变更字段（包括变更类型）
            function addChangeItem(t){
                var td = t.parents("td"),
                    nextTd = td.next();
                var guid = guidGen();

                var cSelect = $('<select lay-filter="fieldsSelect5" class="fieldsSelect" name="change-field"></select>').html(changeFieldsHtml),
                    cSpan = $('<div style="position: relative;margin-right: 80px;" class="change-panel"></div>').attr("key",guid).append(cSelect).append('<a href="javascript:;" class="remove-field" style="color: red;position: absolute;top: 10px; right: -40px;">删除</a>'),
                    vSpan = $('<div></div>').attr("key",guid).append(vValSpan);

                cSelect.trigger("change");

                td.append('<p><br /></p>').append(cSpan);
                nextTd.append('<p><br /></p>').append(vSpan);

                $(vValSpan).trigger("change");
            }

            //变换类型为级联
            form.on('select(changeType)', function(data){
                if (data.value=='8'){
                    $(data.elem).siblings('.done').show();
                }else {
                    $(data.elem).siblings('.done').hide();
                }
            });
            $(document).on('click','.done',function () {
                layer.open({
                    title:'级联设置',
                    type: 1,
                    shade: 0.3,
                    area: ['800px', '400px'],
                    btn : [ "确定", "取消" ],
                    content: $(this).siblings('div.doneLayer'),
                    success:function (layero,index) {
                    },
                    yes:function (index,layero) {
                    }
                });
            })
            $("#add").click(function(){
                $("tr.empty").remove();
                $('#fieldTable').append(getNewTr(0));
                form.render(); //更新全部
            });
            //保存
            $("#save").click(function(){
                var json = [];
                if ($("#fieldTable tbody tr").eq(0).children('td').length>1){
                    $.each($("#fieldTable tbody tr"),function (k,v) {
                        var jsonData={};
                        jsonData.id = $(v).find("input[name=id]").val();
                        jsonData.modelId = modelId;
                        jsonData.nodeId = $(v).find("select[name=nodeId]").val();
                        jsonData.nodeName = $(v).find("select[name=nodeId] option:selected").text();
                        jsonData.chooseField = [];
                        jsonData.changeField = [];
                        $.each($(v).children('td').eq(2).children('div'),function (index,value) {
                            var chooseFieldObj = {};
                            chooseFieldObj.id=$(value).find('select').val();
                            chooseFieldObj.name=$(value).find('select option:selected').text();
                            // chooseFieldObj.key=$(value).parent('td').next().children("div[key="+$(value).attr('key')+"]").find('select').val();
                            chooseFieldObj.value=$(value).parent('td').next().children("div[key="+$(value).attr('key')+"]").find('select option:selected').text();
                            jsonData.chooseField.push(chooseFieldObj);
                        });
                        $.each($(v).children('td').eq(4).children('div'),function (index,value) {
                            var changeFieldObj = {};
                            changeFieldObj.id=$(value).find('select').val();
                            changeFieldObj.name=$(value).find('select option:selected').text();
                            // changeFieldObj.key=$(value).parent('td').next().children("div[key="+$(value).attr('key')+"]").find('select').val();
                            changeFieldObj.type=$(value).parent('td').next().children("div[key="+$(value).attr('key')+"]").find('select').val();
                            changeFieldObj.fieldtype=$(value).find('select option:selected').attr('fieldtype');
                            jsonData.changeField.push(changeFieldObj);
                        });
                        json.push(jsonData);
                    });
                    $.ajax({
                        url: serverPath.workflowPath + setter.workflowLinkPath + "bpmGangedSet/save",
                        type: "post",
                        data: {
                            json:JSON.stringify(json),
                            modelId:modelId
                        },
                        dataType: 'json',
                        success: function (data) {
                            if (data.code==0){
                                layer.msg(data.msg,{icon:6});
                            }else {
                                layer.msg(data.msg,{icon:5});
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                        }
                    })
                }else {
                    layer.msg('请添加数据！',{icon:0});
                }

            });

            $("#del").click(function () {
                var isChecked = $('input.chk:checked');
                if(isChecked.length==0){
                    layer.msg("请选择记录！",{icon: 5})
                }
                layer.confirm("确定要删除吗？", {
                    btn: ['确定','取消'],
                    title: "提示",
                    yes: function () {
                        isChecked.each(function () {
                            $(this).parents("tr").remove();
                            layer.close(layer.index);
                        });
                        if ($("tr").length<2){
                            $('#fieldTable').append('<tr class="empty"><td colspan="6">当前没有记录。</td></tr>')
                        }
                    }
                })
            });

            //添加所选字段
            $(document).off('click','.add-choose-field').on('click','.add-choose-field',function () {
                addChooseItem($(this));
                form.render(); //更新全部
            });

            //添加变换字段
            $(document).off('click','.add-change-field').on('click','.add-change-field',function () {
                addChangeItem($(this));
                form.render(); //更新全部
            });

            //删除
            $(document).on('click','.remove-field',function () {
                var span = $(this).parent("div"),
                    td = $(this).parent().parent("td"),
                    nextTd = td.next();
                span.prev("p").remove();
                span.remove();
                $("div[key='"+span.attr("key")+"']",nextTd).prev("p").remove();
                $("div[key='"+span.attr("key")+"']",nextTd).remove();
            })
        })
    </script>
